package com.ry.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ry.novel.mapper.NewsMapper;
import com.ry.novel.model.dto.NewsInfo;
import com.ry.novel.model.dto.condition.NewsQuery;
import com.ry.novel.model.entity.News;
import com.ry.novel.service.NewsService;
import com.ry.novel.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ry
 * @since 2022-04-10 15:33
 **/
@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public Page<NewsInfo> queryNews(NewsQuery newsQuery) {
        Page<News> page = new Page<>(newsQuery.getPage(),newsQuery.getSize());
        Page<NewsInfo> infoPage = new Page<>(newsQuery.getPage(),newsQuery.getSize());

        QueryWrapper<News> wrapper = new QueryWrapper<>();
        if (null != newsQuery.getTitle()){
            wrapper.like("title",newsQuery.getTitle());
        }

        newsMapper.selectPage(page, wrapper);
        List<NewsInfo> infos = page.getRecords().stream().map(news -> {
            NewsInfo newsInfo = new NewsInfo();
            newsInfo.setId(news.getId());
            newsInfo.setTitle(news.getTitle());
            newsInfo.setContent(news.getContent());
            newsInfo.setReadCount(news.getReadCount());
            newsInfo.setCreateTime(DateUtil.format(news.getCreateTime()));
            newsInfo.setUpdateTime(DateUtil.format(news.getUpdateTime()));


            return newsInfo;
        }).collect(Collectors.toList());

        infoPage.setRecords(infos);
        infoPage.setTotal(page.getTotal());

        return infoPage;
    }

    @Override
    public void addNews(NewsInfo info) {
        News news = new News();
        news.setTitle(info.getTitle());
        news.setContent(info.getContent());
        news.setReadCount(info.getReadCount());
        news.setCreateTime(LocalDateTime.now().toString());
        news.setUpdateTime(LocalDateTime.now().toString());

        newsMapper.insert(news);
    }

    @Override
    public void updateNews(NewsInfo info) {
        News news = new News();
        news.setId(info.getId());
        news.setTitle(info.getTitle());
        news.setContent(info.getContent());
        news.setReadCount(info.getReadCount());
        news.setUpdateTime(LocalDateTime.now().toString());

        newsMapper.updateById(news);
    }

    @Override
    public void deleteNews(Long id) {
        newsMapper.deleteById(id);
    }
}
